#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include <glib.h>

#include "md5.h"
#include "mod.h"

#define KEY_SIZE 16

//http://videopornazzi.com


GHashTable *table;

	const char *
cy(const unsigned char digest[])
{
	static const char *hex = "0123456789abcdef";
	char *str = malloc(KEY_SIZE * 2 +1);
	int i;

	for (i = 0; i < KEY_SIZE ; i++)
	{
		str[i*2]   = hex[digest[i] >> 4];
		str[i*2+1] = hex[digest[i] & 0x0f];
	}
	str[i*2] = '\0';

	return str;
}

long curlx_tvdiff(struct timeval newer, struct timeval older)
{
	  return (newer.tv_sec-older.tv_sec)*1000+
		      (newer.tv_usec-older.tv_usec)/1000;
}
int process(squid_t *req){
	char res[MOD_URL_MAX];
	char *p;
	char *k;
	int ret=-1;
	struct timeval tv;
	struct timeval tv2;

	p = strchr(req->url,':');
	p+=3;
	memset(res,0,sizeof(res));
	md5_buffer(p,strlen(p),&res);

	k=cy(res);
	

	gettimeofday(&tv,NULL);
	if(g_hash_table_lookup(table,k)!=NULL){
		req->resp = strdup("http://www.stopbadware.org/");
		ret=0;
	}
//	sleep(1);
	gettimeofday(&tv2,NULL);
	printf("spent %ld\n",curlx_tvdiff(tv2,tv));

	free(k);
	return ret;
}

int init(){
	FILE *fp;
	char buf[KEY_SIZE*2+2];
	char *p;
	char *k;

	table = g_hash_table_new(g_str_hash,g_str_equal);

	fp = fopen("./hash","r");
	while(fgets(buf,KEY_SIZE*2+2,fp)){
		p=strchr(buf,'\n');
		*p=0;
		k = strdup(buf);
		g_hash_table_insert(table,k,k);
	}
	fclose(fp);

return 0;
}
int endi(){
printf("closing...\n");
return 0;
}

DECLARE_MOD("google",init,process,endi)
